package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Order;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.rmi.runtime.Log;

import javax.print.DocFlavor;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器执行的逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求与响应对象
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getURI().getPath();
        // 判断请求地址是否需要鉴权
        // 直接判断请求地址中是否包含"/login"
        if (path.contains("/login")){
        // 包含,直接放行
           return chain.filter(exchange);

        }
        // 从请求对象中获取请求头
        String token = request.getHeaders().getFirst("token");
        // 不包含说明需要鉴权,,此时判断请求头中是否包含token
        if (!StringUtils.isEmpty(token)){
            try{
                // 解析成功
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                // 有token,判断是否有效
                int status = AppJwtUtil.verifyToken(claimsBody);
                if (status == -1 || status == 0){
                    // 有效,从token中提取用户id
                    Object userId = claimsBody.get("userId");
                    // 将用户id放回到请求头中,将带有用户id的请求头转发给后端的微服务
                    request.mutate().header("userId",userId.toString());
                    return chain.filter(exchange);
                }
            }catch (Exception e){
                // 记录异常日志
                log.error(e.getMessage());
            }
        }
        // 解析失败
        //设置返回状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //直接响应客户端,不再往后端转发
        return response.setComplete();
    }

    /**
     *
     * 过滤器执行的顺序,数字越小,优先级越大
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
